package com.whmnx.chitchat.ui.chat;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.orhanobut.logger.Logger;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.whmnx.chitchat.R;
import com.whmnx.chitchat.base.BaseActivity;
import com.whmnx.chitchat.bean.BaseBean;
import com.whmnx.chitchat.bean.ImgResultBean;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;
import com.whmnx.chitchat.fragment.ChatFragment;
import com.whmnx.chitchat.http.CallBack;
import com.whmnx.chitchat.http.HttpClient;
import com.whmnx.chitchat.main.LoginActivity;
import com.whmnx.chitchat.main.MainActivity;
import com.whmnx.chitchat.utils.FileChooseUtil;
import com.whmnx.chitchat.utils.FileUtil;
import com.whmnx.chitchat.utils.FileUtils;
import com.whmnx.chitchat.utils.PhotoUtil;
import com.whmnx.chitchat.utils.SPUtil;
import com.whmnx.chitchat.utils.UItils;
import com.whmnx.chitchat.view.Watermark;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.whmnx.chitchat.fragment.CustomInputFragment.FILE_SELECT_CODE;
import static com.whmnx.chitchat.ui.my.MyInfoActivity.CODE_CAMERA_REQUEST;
import static com.whmnx.chitchat.ui.my.MyInfoActivity.CODE_GALLERY_REQUEST;
import static com.whmnx.chitchat.ui.my.MyInfoActivity.CODE_RESULT_REQUEST;
import static com.whmnx.chitchat.ui.my.MyInfoActivity.OUTPUT_X;
import static com.whmnx.chitchat.ui.my.MyInfoActivity.OUTPUT_Y;

/**
 * author : huang
 * date   : 2020/7/21 0021 17:57
 * version: 1.0
 * @author Administrator
 */
public class ChatActivity extends BaseActivity {
    private ChatFragment mChatFragment;
    private ChatInfo mChatInfo;
    public  IUIKitCallBack mCallback;

    private Uri imageUri;
    private Uri cropImageUri;
    private Uri newUri;
    private  String size;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.chat_activity);
        setHead_title(View.GONE);
    }

    @Override
    protected void loadData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            startSplashActivity();
        } else {
            mChatInfo = (ChatInfo) bundle.getSerializable(Constants.CHAT_INFO);
            String com = SPUtil.getString(Constants.COM);
            String dep = SPUtil.getString(Constants.DEP);
            String nick = SPUtil.getString(Constants.NICKNAME);
            Watermark.getInstance().show(this, dep + com + nick);
            if (mChatInfo == null) {
                startSplashActivity();
                return;
            }
            mChatFragment = new ChatFragment();
            mChatFragment.setArguments(bundle);
            getSupportFragmentManager().beginTransaction().replace(R.id.empty_view, mChatFragment).commitAllowingStateLoss();
        }
    }

    private void startSplashActivity() {
        Intent intent = new Intent(ChatActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    public  void setCallback(IUIKitCallBack callback) {
        mCallback = callback;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                   // PhotoUtil.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    List<File> files = new ArrayList<>();
                    File file = new File(FileUtil.compressImage(fileUri.getPath()));
                    files.add(file);
                    Logger.i(fileUri.getPath());
                    updatePhotoFile(files,1);
                    break;
                case CODE_GALLERY_REQUEST:
                   // cropImageUri = Uri.fromFile(fileCropUri);
                   // newUri = Uri.parse(PhotoUtil.getPath(this, data.getData()));
                    //String s = PhotoUtil.getPath(this, data.getData());
                  /*  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                      //  newUri = FileProvider.getUriForFile(this, "com.whmnx.chitchat.FileProvider", new File(newUri.getPath()));
                    }*/
                    try {
                        Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                        String[] filePathColumn = { MediaStore.Images.Media.DATA };
                        Cursor cursor =getContentResolver().query(selectedImage,
                                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        //获取照片路径
                        String picturePath = cursor.getString(columnIndex);
                        cursor.close();
                        if (TextUtils.isEmpty(picturePath)){
                            UItils.showToastSafe("图片不存在");
                            return;
                        }
                        List<File> files2 = new ArrayList<>();
                        File file3 = new File(FileUtil.compressImage(picturePath));
                        files2.add(file3);
                        updatePhotoFile(files2,1);
                     //   Bitmap bitmap= BitmapFactory.decodeFile(picturePath);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                   // Logger.i(newUri.getPath());
                //    files.add(file);
                    break;
                    //选择文件
                case FILE_SELECT_CODE:
                    String  path;
                     Uri uri = data.getData();

                  //  String  path = FileChooseUtil.getInstance(this).getChooseFileResultPath(uri);
                   // String  path = FileChooseUtil.getInstance(this).splicingPath(uri);

                    //4.4以后
                   if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                          path = FileUtils.getPath(this, uri);
                    } else {//4.4以下下系统调用方法
                          path = FileUtils.getLocalPath(this,uri);
                    }

                    List<File> files3 = new ArrayList<>();
                  //  Uri  newUri = Uri.parse(PhotoUtil.getPath(this, data.getData()));
                   // PhotoUtil.getPath(this, data.getData());
                    File file4 = new File(path);
                    files3.add(file4);
                    size = FileUtil.getAutoFileOrFilesSize(path);
                    updatePhotoFile(files3,3);
                    break;
                default:
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void updatePhotoFile(List<File> files,int type2) { 
        String url = Constants.UPLOADHEADIMG + "?foldername=PhotoFile";
        HttpClient.postImg(this, url,files, new CallBack<List<ImgResultBean>>() {
            @Override
            public void onSuccess(List<ImgResultBean> baseBean) {
                String url;
                    //上传的图片地址
                    if (type2 == 3){
                         url = baseBean.get(0).fullPath + "##" + baseBean.get(0).fileName + "##" + size;
                    }else {
                         url =  baseBean.get(0).fullPath;
                         List<String> imgList = new ArrayList<>();
                         imgList.add(url);
                         Constants.IMGLIST2 = imgList;
                    }
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setMessageKey(EventConstants.SENDIMG);
                    messageEvent.setMessageValue(url + "—" + type2);
                    EventBus.getDefault().post(messageEvent);
            }
        });
    }
}
